layui.use(['form','tree','element','dtree','table','laytpl','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;
    var timer = null;//计时器
    var dtree = layui.dtree;

    //验证当前用户是否登录
    var _ticket = $.cookie("token");
    if(_ticket != null || _ticket != ""){
        $.ajax({
            url : "http://106.75.154.40:8083/user/token/" + _ticket,//单点登录链接
            dataType : "jsonp",
            type : "GET",
            success : function(data){
                if (data.code == 200) {
                    window.username = data.data.user.loginName;
                    $("#cur-user").html(username);

                    //场景数据
                    var treeData = {
                        elem: '#tree' //指定元素
                        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
                        , click: function (item) { //点击节点回调
                            //查询当前场景下的设备
                            $.get("/equipment/query?sceneId=" + item.id,function (data) {
                                if (data.data.length != 0) {
                                    init(data.data[0].id);
                                    /*$("#equipment").html("当前设备：" + data.data[0].name);*/
                                    //加载当前场景下设备列表
                                    $("#equipment-list").html("");
                                    $.each(data.data,function (i, ele) {
                                        $("#equipment-list").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
                                        form.render('select');
                                    });
                                    //刷新设备对应的数据采集项
                                    form.on('select(equipment-list)',function (data) {
                                        init(data.value);
                                    });
                                } else {
                                    layer.msg("啊哦，找不到设备，切换场景试试？",{icon:5})
                                }
                            });
                            $("#cur-scenery").html("当前场景：" + item.name);
                            $("#cur-addr").html("地址：" + item.address);
                            // 百度地图API功能
                            var map = new BMap.Map("allmap");
                            var point = new BMap.Point(item.longitude, item.latitude);
                            map.centerAndZoom(point, 15);
                            var marker = new BMap.Marker(point);  // 创建标注
                            map.addOverlay(marker);               // 将标注添加到地图中
                            marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
                        },
                        nodes:null
                    };

                    //异步加载设备所处场景数据
                    $.get('/user/scene/tree?userId=' + data.data.user.id,function(data) {
                        if (data.data.length != 0) {
                            data.data[0].spread = true;
                            var children = data.data[0].children;
                            if (children != null && children.length != 0) {
                                $.each(children,function (i, ele) {
                                    ele.spread = true;
                                });
                            }
                        }
                        treeData.nodes = data.data;
                        layui.tree(treeData);
                        $("#tree-scenery").hide();
                    });

                    $.get('/user/scene/equipment?userId=' + data.data.user.id,function (data) {
                        if (data.data.length != 0) {
                            init(data.data[0].id);
                            //当前设备
                            /*$("#equipment").html("当前设备：" + data.data[0].name);*/
                            $("#equipment-list").append('<option value="'+ data.data[0].id +'">'+ data.data[0].name +'</option>');
                            form.render('select');

                            //设置所处的场景
                            $.get("/scene/" + data.data[0].sceneId,function (data) {
                                $("#loading-map").hide();
                                $("#cur-scenery").html("当前场景：" + data.name);
                                $("#cur-addr").html("地址：" + data.address);
                                // 百度地图API功能
                                var map = new BMap.Map("allmap");
                                var point = new BMap.Point(data.longitude, data.latitude);
                                map.centerAndZoom(point, 15);
                                var marker = new BMap.Marker(point);  // 创建标注
                                map.addOverlay(marker);               // 将标注添加到地图中
                                marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
                            });
                        } else {
                            layer.msg("找不到设备，请先添加设备！",{icon:5});
                        }
                    });

                    //设置默认设备
                    /*$.get("/equipment/query",function (data) {
                        if (data.data.length != 0) {
                            init(data.data[0].id);
                            //当前设备
                            /!*$("#equipment").html("当前设备：" + data.data[0].name);*!/
                            $("#equipment-list").append('<option value="'+ data.data[0].id +'">'+ data.data[0].name +'</option>');
                            form.render('select');

                            //设置所处的场景
                            $.get("/scene/" + data.data[0].sceneId,function (data) {
                                $("#loading-map").hide();
                                $("#cur-scenery").html("当前场景：" + data.name);
                                $("#cur-addr").html("地址：" + data.address);
                                // 百度地图API功能
                                var map = new BMap.Map("allmap");
                                var point = new BMap.Point(data.longitude, data.latitude);
                                map.centerAndZoom(point, 15);
                                var marker = new BMap.Marker(point);  // 创建标注
                                map.addOverlay(marker);               // 将标注添加到地图中
                                marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
                            });
                        } else {
                            layer.msg("找不到设备，请先添加设备！",{icon:5});
                        }
                    });*/
                } else {
                    layer.confirm('用户登录已过期，请中重新登录', {icon: 3, title: '提示信息'}, function (tips) {});
                    window.location.href = "http://106.75.154.40:8083/login";
                }
            }
        });
    } else {
        layer.confirm('用户登录已过期，请中重新登录', {icon: 3, title: '提示信息'}, function (tips) {});
        window.location.href = "http://106.75.154.40:8083/login";
    }


    /**
     * 初始化数据
     */
    function init(equipmentId) {
        if (equipmentId == null || equipmentId == "") {
            return;
        }
        //实时采集数据
        setData();
        /*clearInterval(timer);
        timer = setInterval(function () {
            setData();
        },60000);*/

        //控制设备以及按钮
        $.get('/ctrlequipment/query?equipmentId=' + equipmentId,function (ctrlEquipment) {
            $.each(ctrlEquipment.data,function (i, ele) {
                var btnHtml = '';
                var ctrlEquip = ele;
                $.ajax({
                    url : '/ctrlequipment/button/list?ctrlEquipmentId=' + ele.id,
                    async: false,
                    success: function (data) {
                        $.each(data.data,function (i, ele) {
                            if (ele.operationType == 0) {
                                btnHtml += '<button  class="layui-btn layui-btn-normal open '+ (ctrlEquip.isService == 1?'layui-btn-disabled':'') +'" ' + (ctrlEquip.isService == 1?'disabled':'') +' data-ctrtype="'+ ele.ctrlType +'" data-option="'+ ele.operationType +'" data-channel="'+ ele.ctrlEquipmentId +'" data-channelno="'+ ele.channelNo +'" lay-event="open">'+ ele.buttonName +'</button>';
                            } else {
                                btnHtml += '<button class="layui-btn layui-btn-danger close '+ (ctrlEquip.isService == 0?'layui-btn-disabled':'') +'" '+ (ctrlEquip.isService == 0?'disabled':'') +' data-ctrtype="'+ ele.ctrlType +'" data-option="'+ ele.operationType +'" data-channel="'+ ele.ctrlEquipmentId +'" data-channelno="'+ ele.channelNo +'"  lay-event="close">'+ ele.buttonName +'</button>';
                            }
                        });
                    }
                });

                var innerHtml = '<div class="layui-inline" style="margin: 5px;">' +
                    '        <a class="btn-box" data-type="reload" style="height: 140px;">' +
                    '            <div id="tempDiv">' +
                    '                <h4 class="title">'+ ele.name +'</h4>' +
                    '                <span class="layui-badge-dot btn-status" style="display: inline-block;padding: 2px;margin-right: 5px;'+ (ele.isService == 0?'':'background:#1e9fff;') +'"></span>' +
                    '                <span class="btn-status-text">'+ (ele.isService == 0?'已关闭':'已开启') +'</span>' +
                    '            </div>' + btnHtml +
                    '        </a>' +
                    '    </div>';

                $("#ctrol-equipment").append(innerHtml);
            });

            //设备控制事件
            $("#ctrol-equipment .btn-box .open").click(function () {
                var that = this;
                layer.open({
                    type: 0,
                    content: '是否要打开' + $("#ctrol-equipment .btn-box .title").html() + '?',
                    icon:1,
                    yes(index){
                        $(that).html('<i style="font-size: 16px !important;" class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i>');
                        var dataObj = {};
                        dataObj.ctrlEquipmentId = $(that).data("channel");
                        dataObj.operatorId = '1';//操作者
                        dataObj.operateType = $(that).data("ctrtype");
                        dataObj.returnResult = "-1";//初始化结果
                        dataObj.remarks = $(that).data("channel");
                        $.post('/ctrlequipment/log/add',dataObj,function (data) {
                            if (data.code == 200) {
                                $(that).html("开启").addClass('layui-btn-disabled').attr("disabled","disabled");
                                $(that).next().removeClass('layui-btn-disabled').attr("disabled",false);
                                $(that).parent().find(".btn-status").css("background","#1e9fff");
                                $(that).parent().find(".btn-status-text").html("已开启");
                            } else {
                                $(that).html("开启");
                                layer.msg(data.message);
                            }
                        });
                        layer.close(index);
                    }
                });
            });
            $("#ctrol-equipment .btn-box .close").click(function () {
                var that = this;
                layer.open({
                    type: 0,
                    content: '是否要关闭' + $("#ctrol-equipment .btn-box .title").html() + '?',
                    icon:1,
                    yes(index){
                        $(that).html('<i style="font-size: 16px !important;" class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i>');
                        var dataObj = {};
                        dataObj.ctrlEquipmentId = $(that).data("channel");
                        dataObj.operatorId = '1';
                        dataObj.operateType = $(that).data("ctrtype");
                        dataObj.returnResult = "-1";
                        dataObj.remarks = $(that).data("channel");
                        $.post('/ctrlequipment/log/add',dataObj,function (data) {
                            if (data.code == 200) {
                                $(that).html("关闭").addClass('layui-btn-disabled').attr("disabled","disabled");
                                $(that).prev().removeClass('layui-btn-disabled').attr("disabled",false);
                                $(that).parent().find(".btn-status").css("background","#FF5722");
                                $(that).parent().find(".btn-status-text").html("已关闭");
                            } else {
                                $(that).html("关闭");
                                layer.msg(data.message);
                            }
                        });
                        layer.close(index);
                    }
                });
            });
        });

        /**
         * 设置采集数据
         */
        function setData() {
            $.get("/equipment/channel/query?equipmentId=" + equipmentId,function (channel) {
                var checkItemLength = channel.count;
                if (checkItemLength == 0) {
                    return null;
                }
                $.get("/search/datarecord/page/query?page=0&limit=100&equipmentId=" + equipmentId,function (data) {
                    //当前设备的检测项目
                    var checkItemArr = [];
                    $("#online-data").html("");
                    $("#data-show").html("");

                    //若无数据
                    if (data.data.length <= 0) {
                        $("#online-data").html('<p align="center">暂无数据</p>')
                        $("#data-show").html('<p align="center">暂无数据</p>');
                    }

                    $.each(data.data,function (i, ele) {
                        if (contains(checkItemArr,ele.checkItemId) != -1 && checkItemArr.length <= checkItemLength) {
                            var innerHtml = '<div id="monitor-data'+ i +'" style="display: inline-block;margin: 5px;width: 31%;height: 250px;border: solid 1px #f5f5f5;box-shadow: 2px 2px 5px #f5f5f5;" >' +
                                '</div>';
                            $("#online-data").append(innerHtml);
                            //加入检测项目数组
                            checkItemArr.unshift(ele.checkItemId);
                            //当前场景设备的数据
                            var dataChart = echarts.init(document.getElementById("monitor-data" + i));
                            var option = {
                                tooltip : {
                                    formatter: "{a} <br/>{b} : {c}" + ele.unit,
                                },
                                toolbox: {
                                    feature: {
                                    }
                                },

                                series: [
                                    {
                                        name: '业务指标',
                                        type: 'gauge',
                                        startAngle: 180, //开始角度 左侧角度
                                        endAngle: 0, //结束角度 右侧
                                        detail: {
                                            formatter: '{value}' + ele.unit,
                                            fontSize: 20,
                                            /*borderRadius: 3,
                                            backgroundColor: '#fff',
                                            fontFamily: 'Arial',
                                            width: 100,*/
                                        },
                                        data: [{value: ele.processedData, name: ele.checkItemName}],
                                        axisLine: {            // 坐标轴线
                                            lineStyle: {       // 属性lineStyle控制线条样式
                                                width: 15,
                                                color: [[0.2, '#91c7ae'], [0.8, '#4EA1DB'], [1, '#FF5722']]//[[0.2, '#91c7ae'], [0.8, '#2F4056'], [1, '#c23531']]
                                            }
                                        },
                                        /*axisTick: {            // 坐标轴小标记
                                            length: 0,        // 属性length控制线长
                                            lineStyle: {       // 属性lineStyle控制线条样式
                                                color: 'auto'
                                            }
                                        },*/
                                        splitLine: {           // 分隔线
                                            length: 10,         // 属性length控制线长
                                            lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                                                color: 'auto',
                                            }
                                        }
                                    }
                                ]
                            };
                            dataChart.setOption(option, true);
                            $("#loading-monitor").hide();

                            //设置侧栏数据
                            var dataHtml = '<div style="width: 100%; height: 80px;margin: 5px 0;padding: 3px 30px;border: solid 1px #f5f5f5;box-shadow: 2px 2px 5px #f5f5f5;">' +
                                '            <div style="overflow: hidden;">' +
                                '                <span class="left-data-title" style="float: left">'+ ele.checkItemName +'</span>' +
                                '                <span style="float: right;line-height: 40px"><span style="font-size: 16px;">'+ ele.processedData + '</span>&nbsp;<span style="color: #666666;">' + ele.unit +'</span></span>' +
                                '            </div>' +
                                '            <p style="color: #666666;">('+ ele.equipmentName +')</p>' +
                                '        </div>';
                            $("#data-show").append(dataHtml);
                        }

                    });

                    //如果有监控设备
                    $.ajax({
                        url: "/equipment/associate/query?equipmentId=" + equipmentId,
                        type: 'post',
                        async: false,
                        success: function (data) {
                            if (data.data.length != 0) {
                                $("#online-data").html('');
                                var innerHtml = '<div class="vedio-display">' +
                                    '                <video id="myPlayer" style="height: 450px;width: 100%;" poster="" controls playsInline webkit-playsinline autoplay>' +
                                    '                    <source src="'+ data.data[0].deviceUrl +'" />' +
                                    '                </video>' +
                                    '            </div>';
                                $("#online-data").append(innerHtml);
                                //视频播放
                                var player = new EZUIPlayer('myPlayer');
                                player.on('error', function(){
                                    //播放失败
                                    $("#online-data").html('播放失败，请检查网络或设备');

                                    //重新加载
                                    $.get("/search/datarecord/page/query?page=0&limit=100&equipmentId=" + equipmentId,function (data) {
                                        //当前设备的检测项目
                                        var checkItemArr = [];
                                        $("#online-data").html("");
                                        // $("#data-show").html("");

                                        //若无数据
                                        if (data.data.length <= 0) {
                                            $("#online-data").html('<p align="center">暂无数据</p>')
                                            // $("#data-show").html('<p align="center">暂无数据</p>');
                                        }

                                        $.each(data.data,function (i, ele) {
                                            if (contains(checkItemArr,ele.checkItemId) != -1 && checkItemArr.length <= checkItemLength) {
                                                var innerHtml = '<div id="monitor-data'+ i +'" style="display: inline-block;margin: 5px;width: 31%;height: 250px;border: solid 1px #f5f5f5;box-shadow: 2px 2px 5px #f5f5f5;" >' +
                                                    '</div>';
                                                $("#online-data").append(innerHtml);
                                                //加入检测项目数组
                                                checkItemArr.unshift(ele.checkItemId);
                                                //当前场景设备的数据
                                                var dataChart = echarts.init(document.getElementById("monitor-data" + i));
                                                var option = {
                                                    tooltip : {
                                                        formatter: "{a} <br/>{b} : {c}" + ele.unit,
                                                    },
                                                    toolbox: {
                                                        feature: {
                                                        }
                                                    },

                                                    series: [
                                                        {
                                                            name: '业务指标',
                                                            type: 'gauge',
                                                            startAngle: 180, //开始角度 左侧角度
                                                            endAngle: 0, //结束角度 右侧
                                                            detail: {
                                                                formatter: '{value}' + ele.unit,
                                                                fontSize: 20,
                                                                /*borderRadius: 3,
                                                                backgroundColor: '#fff',
                                                                fontFamily: 'Arial',
                                                                width: 100,*/
                                                            },
                                                            data: [{value: ele.processedData, name: ele.checkItemName}],
                                                            axisLine: {            // 坐标轴线
                                                                lineStyle: {       // 属性lineStyle控制线条样式
                                                                    width: 15,
                                                                    color: [[0.2, '#91c7ae'], [0.8, '#4EA1DB'], [1, '#FF5722']]//[[0.2, '#91c7ae'], [0.8, '#2F4056'], [1, '#c23531']]
                                                                }
                                                            },
                                                            /*axisTick: {            // 坐标轴小标记
                                                                length: 0,        // 属性length控制线长
                                                                lineStyle: {       // 属性lineStyle控制线条样式
                                                                    color: 'auto'
                                                                }
                                                            },*/
                                                            splitLine: {           // 分隔线
                                                                length: 10,         // 属性length控制线长
                                                                lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                                                                    color: 'auto',
                                                                }
                                                            }
                                                        }
                                                    ]
                                                };
                                                dataChart.setOption(option, true);
                                                $("#loading-monitor").hide();
                                            }

                                        });
                                    });
                                });
                                player.on('play', function(){
                                });
                                player.on('pause', function(){
                                });
                            }
                        }
                    });
                });
            });

        }

        //加载设备当前通道数据
        $.get("/equipment/channel/query?equipmentId=" + equipmentId,function (channel) {
            var checkItemLength = channel.count;
            if (checkItemLength == 0) {
                return null;
            }
            $("#check-item").html("");
            $.each(channel.data,function (i, ele) {
                if (i == 0) {
                    $("#check-item").append('<li class="layui-this" data-id="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</li>');
                    //加载当前通道的数据
                    initChart(equipmentId,ele.collectChannelApplicateTypeId);
                } else {
                    $("#check-item").append('<li class="" data-id="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</li>');
                }
            });

            //绑定事件，切换当前检测项目，刷新数据统计
            $("#check-item li").click(function () {
                var checkItemId = $(this).data("id");
                initChart(equipmentId,checkItemId);
            });
        });

        /**
         * 初始化统计图
         * @param equipmentId
         * @param checkItemId
         */
        function initChart(equipmentId,checkItemId) {
            var searchObj = {};
            searchObj.page = 0;
            searchObj.limit = 100;//设置默认最大查询范围
            searchObj.equipmentId = equipmentId;
            searchObj.checkItemId = checkItemId;

            $.get("/search/datarecord/page/query?",searchObj,function (data) {
                //当前设备的检测项目
                if (data.data.length <= 0) {
                    //关闭加载动画
                    $("#echart-show").html('<div align="center">没有与之匹配的数据</div>')
                }
                $("#echart-show").html("");
                //x轴时间组件
                var xAxisdataArr = [];
                var seriesArr = [];
                var checkMessage = {};
                $.each(data.data,function (j, ele) {
                    var date = new Date(ele.acquisitionTime);
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.unshift(dateStr);
                    seriesArr.unshift(ele.processedData);
                    checkMessage.title = ele.checkItemName + "趋势";
                    checkMessage.legendData = ele.checkItemName;
                    checkMessage.seriesName = ele.checkItemName;
                    checkMessage.yAxisformatter = ele.unit;
                });
                setTrendData(checkItemId,xAxisdataArr,seriesArr,checkMessage);
            });

        }

        /**
         * 设置检测项目相应的数据统计
         * @param checkItemId
         * @param xAxisdataArr
         * @param seriesArr
         * @param checkMessage
         */
        function setTrendData(checkItemId,xAxisdataArr, seriesArr, checkMessage) {
            var innerHtml = '<div id="echart-show-'+ checkItemId +'" class="layui-tab-item layui-show" style="width: 100%; height: 450px;">' +
                '            </div>';
            $("#echart-show").append(innerHtml);
            //折线图
            var lineChart = echarts.init(document.getElementById('echart-show-' + checkItemId));
            var option = {
                title: {
                    text: checkMessage.title,
                    subtext: ' '
                },
                tooltip: {
                    trigger: 'axis'
                },
                color:"#0f9ac3",
                legend: {
                    data:[checkMessage.legendData]
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: {readOnly: false},
                        magicType: {type: ['line', 'bar']},
                        restore: {},
                        saveAsImage: {}
                    }
                },
                dataZoom: {
                    show: true,
                    realtime : true,
                    start: 0,
                    end: 18,
                    height: 20,
                    backgroundColor: '#f8f8f8',
                    dataBackgroundColor: '#e4e4e4',
                    fillerColor: '#87cefa',
                    handleColor: '#87cefa',
                },
                xAxis:  {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxisdataArr
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} ' + checkMessage.yAxisformatter
                    }
                },
                series: [
                    {
                        name:checkMessage.seriesName,
                        type:'line',
                        data:seriesArr,
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        },
                        lineStyle: {
                            normal: {
                                color:"#0f9ac3"
                            }
                        }
                    }
                ]
            };
            lineChart.setOption(option);
        }
    }


    /**
     * 判断数组中是否存在元素
     * @param arr
     * @param obj
     * @returns {number}
     */
    function contains(arr, obj) {
        if (arr.length != 0) {
            for (var i = 0;i < arr.length;i++) {
                if(arr[i] == obj) {
                    return -1;
                }
            }
        }
        return 0;
    }

    /**
     * 获取当前时间，以solr中date的格式 2018-08-27T02:28:58Z
     * @param date
     * @returns {string}
     */
    function getSolrDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
        var day = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate();
        var hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours();
        var minutes = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes();
        var seconds = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds();
        var dateStr = year + '-' + month + '-' + day + 'T' + hour + ':' + minutes + ':' + seconds + 'Z';
        return dateStr;
    }


});